package com.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.common.QiniuException;
import com.verify.UserVerify;
import com.domain.Issue;
import com.domain.LabelWithIssue;
import com.domainVO.IssueLabelIdsVO;
import com.domainVO.IssueUserLabeCommentlVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.service.IIssueService;
import com.service.ILabelService;
import com.service.ILabelWithIssueService;
import com.util.UserUtil;
import com.verify.WeiXinVerify;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import living.com.result.ApiResult;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;


/**
 * <p>
 *     处理互助模块中提出问题的控制器
 * </p>
 * @author 大忽悠
 * @create 2022/2/8 20:51
 */
@Api(tags = "问题请求集合")
@RestController
@RequiredArgsConstructor
public class IssueController {
    private final IIssueService iIssueService;
    private final ILabelService labelService;
    private final ILabelWithIssueService iLabelWithIssueService;
    private static final ObjectMapper objectMapper=new ObjectMapper();

    @UserVerify
    @WeiXinVerify(paramIndex = 0,paramName = "IssueLabelIdsVO",weiXinVerifyType = 2,needImgCheck = true,needVideoCheck = true)
    @ApiOperation("发布问题,成功返回问题id")
    @PostMapping("/issues")
    @ApiOperationSupport(includeParameters = {"issueLabelVO.issue.questionTitle","issueLabelVO.issue.questionDetails"
            ,"issueLabelVO.issue.imgs","issueLabelVO.issue.videos","issueLabelVO.issue.isAnony","issueLabelVO.labelIds"})
    @Transactional(value = "primaryTransactionManager")
    public ApiResult<Integer> postQuestion(@Validated @RequestBody IssueLabelIdsVO issueLabelVO) throws JsonProcessingException {
        Issue issue = issueLabelVO.getIssue();
        String pics = issue.getImgs();
        //判断路径格式
        //判断图片数量是否超过五张
        if(pics!=null&&pics!="")
        {
            //格式正确与否
            if(!(pics.startsWith("[")&&pics.endsWith("]")))
            {
                throw new IllegalArgumentException("路径格式错误");
            }
            List list = objectMapper.readValue(pics, List.class);
            Assert.isTrue(list.size()<=5,"图片最多五张");
        }else
        {
            issue.setImgs(null);
        }
        String videos = issue.getVideos();
        //视频最多一个
        if(videos!=null&&videos!="")
        {
            //格式正确与否
            if(!(videos.startsWith("[")&&videos.endsWith("]")))
            {
                throw new IllegalArgumentException("路径格式错误");
            }
            List list = objectMapper.readValue(videos, List.class);
            Assert.isTrue(list.size()<=1,"视频最多一个");
        }
        else
        {
            issue.setVideos(null);
        }
        //问题可以不与任何标签关联
        if(issueLabelVO.getLabelIds()!=null&&issueLabelVO.getLabelIds().size()!=0)
        {
            //所选择的标签必须是已经存在的
            Assert.isTrue(labelService.listByIds(issueLabelVO.getLabelIds()).size()==issueLabelVO.getLabelIds().size()
                    ,"存在非法标签");
        }
        //设置用户id
        issue.setUserId(UserUtil.getUserId());
        synchronized (this) {
            iIssueService.save(issue);
            //一个问题可能对应多个标签,保存所有映射关系
            issueLabelVO.getLabelIds().forEach(id->{
                iLabelWithIssueService.save(LabelWithIssue.builder().labelId(id).issueId(issue.getId()).build());
            });
        }
        return ApiResult.success(issue.getId());
    }

    @ApiOperation("获取所有问题,按照时间排序,返回问题和提问用户的信息")
    @GetMapping("/issuesByTime")
    public ApiResult<Map<String, Object>> getAllQuestionsByTime(@ApiParam("起始页")@RequestParam Integer startPage,
                                                          @ApiParam("一页多少条数据")@RequestParam Integer pageSize)
    {
        return ApiResult.success(iIssueService.getAllQuestionsByTime(startPage,pageSize));
    }

    @ApiOperation("获取所有问题,按照热度排序,返回问题和提问用户的信息")
    @GetMapping("/issuesByHot")
    public ApiResult<Map<String, Object>> getAllQuestionsByHot(@ApiParam("起始页")@RequestParam Integer startPage,
                                                                @ApiParam("一页多少条数据")@RequestParam Integer pageSize)
    {
        return ApiResult.success(iIssueService.getAllQuestionsByHot(startPage,pageSize));
    }



    @ApiOperation("获取指定id对应的问题")
    @GetMapping("/issue")
    public ApiResult<IssueUserLabeCommentlVO> getTargetQuestion(@ApiParam("问题id")@RequestParam Integer issue_id)
            throws JsonProcessingException {
        return ApiResult.success(iIssueService.getTargetIssue(issue_id));
    }

    @ApiOperation("通过关键字模糊搜索问题")
    @GetMapping("/VagueSearchIssues")
    public ApiResult<Map<String,Object>> VagueSearchQuestions(@ApiParam("关键字")@RequestParam String keyWord,
                                                                         @ApiParam("起始页")@RequestParam Integer startPage,
                                                                         @ApiParam("一页多少条数据")@RequestParam Integer pageSize)
    {
        return ApiResult.success(iIssueService.vagueSearchQuestions(keyWord,startPage,pageSize));
    }

    //@UserVerify
   // @ApiOperation("删除问题")
   // @DeleteMapping("/issue")
    public ApiResult<Boolean> delTargetQuestion(@ApiParam("问题id")@RequestParam Integer issue_id) throws QiniuException, JsonProcessingException {
        return ApiResult.success(iIssueService.delTargetQuestion(issue_id));
    }

    @UserVerify
    @ApiOperation("逻辑删除问题")
    @DeleteMapping("/logicDelIssue")
    public ApiResult<Boolean> logicDelTargetQuestion(@ApiParam("问题id")@RequestParam Integer issue_id) throws QiniuException {
        return ApiResult.success(iIssueService.logicDelTargetQuestion(issue_id));
    }

    @ApiOperation("获取自己提出的问题")
    @GetMapping("/ownIssues")
    public ApiResult<Map<String,Object>> getOwnIssues( @ApiParam("起始页")@RequestParam Integer startPage,
                                                           @ApiParam("一页多少条数据")@RequestParam Integer pageSize)
    {
        return ApiResult.success(iIssueService.getOwnIssues(startPage,pageSize));
    }


    @ApiOperation("获取我点赞过的问题")
    @GetMapping("myLikeIssues")
    public ApiResult<Map<String,Object>> getMyLikeIssues(@ApiParam("起始页")@RequestParam Integer startPage,
                                                         @ApiParam("一页多少条数据")@RequestParam Integer pageSize)
    {
        return ApiResult.success(iIssueService.getMyLikeIssues(startPage,pageSize));
    }

}
